package com.zigong.app.ui.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Pair;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;

import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.zigong.app.R;
import com.zigong.app.application.SiChuanFocusApplication;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.application.Constances;
import com.zigong.app.beans.FUsers;
import com.zigong.app.beans.SerialThirdInfo;
import com.zigong.app.beans.SingleResult;
import com.zigong.app.http.AbsNetCallBack;
import com.zigong.app.http.DMethods;
import com.zigong.app.http.NetUtils;
import com.zigong.app.ui.entity.Clickable;
import com.zigong.app.ui.utils.SkipUtil;
import com.zigong.app.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 登录页面
 */
public class LoginActivity extends BaseActivity implements PlatformActionListener {

    @BindView(R.id.login_thir_qq)
    protected ImageView qq;
    @BindView(R.id.login_thir_wb)
    protected ImageView wb;
    @BindView(R.id.login_thir_wx)
    protected ImageView wx;

    @BindView(R.id.login_et_phone)
    protected CustomFontEditText etPhone;
    @BindView(R.id.login_et_code)
    protected CustomFontEditText etCode;
    @BindView(R.id.login_btn_code)
    protected CustomFontTextView btnCode;
    @BindView(R.id.login_btn_login)
    protected CustomFontTextView btnLogin;
    @BindView(R.id.agree_check)
    protected CheckBox agreeCheck;
    @BindView(R.id.content)
    protected CustomFontTextView content;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;
    private Platform platform;
    private ProgressDialog dialog;


    private final int Time_Count = 60;

    private final int WHAT_TIMW = 901;
    private final int WHAT_TIMW_STOP = 902;
    private final int WHAT_LOGIN_THIRD = 903;

    private final int CODE_REQUEST_BIND = 301;

    private final int CODE_ERROR_THIRD = 402;

    private Handler handler;
    private int time;

    private int openType;

    private boolean isGettingCode, isLogining;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg != null) {
                    parseMsg(msg);
                }
            }
        };
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new ProgressDialog(this);
        dialog.setTitle("登录中...");
        dialog.setCancelable(false);
        initRule();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    private Handler handlerLogin = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_AUTH_CANCEL:
                    // 取消授权
                    platform.removeAccount(true);
                    Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                    break;
                case MSG_AUTH_ERROR: {
                    // 授权失败
                    // Toast.makeText(activity, R.string.auth_error,
                    // Toast.LENGTH_SHORT).show();\\
                    platform.removeAccount(true);
                    Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
                break;
                case MSG_AUTH_COMPLETE:
//                    dialog.dismiss();
                    // 授权成功
                    // Toast.makeText(LoginActivity.this, "授权成功",
//                    // Toast.LENGTH_SHORT).show();
//                    Object[] objs = (Object[]) msg.obj;
//                    String platform = (String) objs[0];
//                    String openId = (String) objs[1];
//                    String avatar = (String) objs[2];
//                    String userName = (String) objs[3];
                    Platform platform = (Platform) msg.obj;
//                    System.out.println(
//                            "platform:" + platform + "  获取到openid:" + openId + " 头像：" + avatar + " userName：" + userName);
//                    login(openId, avatar, userName, platform);
//                    Toast.makeText(LoginActivity.this, "platform:" + platform.getName(), Toast.LENGTH_SHORT).show();
                    PlatformDb platformDb = platform.getDb();
                    login(platformDb);
                    break;

            }

            return false;
        }
    });


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_BIND) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    @OnClick(value = {R.id.login_thir_qq, R.id.login_thir_wb, R.id.login_thir_wx})
    public void thirdLoginClick(View v) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        if (agreeCheck.isChecked()) {
            switch (v.getId()) {
                case R.id.login_thir_qq:
                    pairs.add(new Pair<>("行为类型", "QQ登录"));
                    GridsumWebDissector.getInstance().trackEvent(this, "", "登录", "", 200, pairs);
                    openType = Constances.OPEN_TYPE_LOGIN_QQ;
                    platform = ShareSDK.getPlatform(QQ.NAME);
                    platform.SSOSetting(true);
                    authorize(platform);
                    break;
                case R.id.login_thir_wb:
                    pairs.add(new Pair<>("行为类型", "微博登录"));
                    GridsumWebDissector.getInstance().trackEvent(this, "", "登录", "", 200, pairs);
                    openType = Constances.OPEN_TYPE_LOGIN_WEIBO;
                    platform = ShareSDK.getPlatform(SinaWeibo.NAME);
                    platform.SSOSetting(true);
                    authorize(platform);
                    break;
                case R.id.login_thir_wx:
                    pairs.add(new Pair<>("行为类型", "微信登录"));
                    GridsumWebDissector.getInstance().trackEvent(this, "", "登录", "", 200, pairs);
                    openType = Constances.OPEN_TYPE_LOGIN_WEIXIN;
                    platform = ShareSDK.getPlatform(Wechat.NAME);
                    platform.SSOSetting(true);
                    authorize(platform);
                    break;
            }
        } else {
            toast("请先阅读《用户协议》与《隐私政策》");
        }
    }

    @OnClick(value = {R.id.login_btn_code, R.id.login_btn_login, R.id.login_img_back})
    public void loginClick(View v) {
        switch (v.getId()) {
            case R.id.login_btn_code:
//                String str = HmacSHA256Utils.digest("47723adf-d4bf-455d-b08f-26971f53a999", "241123");
//                JLog.e("sha secret str=" + str);
                if (checkPhone()) {
                    getCode();
                }
                break;
            case R.id.login_btn_login:
                if (checkPhone() && checkCode()) {
                    if (agreeCheck.isChecked()) {
                        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                        pairs.add(new Pair<>("行为类型", "手机登录"));
                        GridsumWebDissector.getInstance().trackEvent(this, "", "登录", "", 200, pairs);
                        login(null);
                    } else {
                        toast("请先阅读《用户协议》与《隐私政策》");
                    }
                }
                break;
            case R.id.login_img_back:
                finish();
                break;
        }
    }

    private boolean checkPhone() {
        if (TextUtils.isEmpty(etPhone.getText().toString()) || !etPhone.getText().toString().matches(Constances.MATCHER_PHONE)) {
            toast(R.string.please_input_valued_phone);
            return false;
        }
        return true;
    }

    private boolean checkCode() {
        if (TextUtils.isEmpty(etCode.getText().toString())) {
            toast(R.string.please_input_code);
            return false;
        }
        return true;
    }

    private synchronized void getCode() {
        btnCode.setEnabled(false);
        final String phone = etPhone.getText().toString();
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("phoneNumber", etPhone.getText().toString());
        NetUtils.getNetAdapter().postGetSingle(getOwnerName(), DMethods.AuthCode, p, new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult s) {
                if (null != s && s.isSuccess()) {
                    SkipUtil.skipToAddUserOperate(LoginActivity.this, getOwnerName(), 21, 0, "发送登录验证码", "", "", phone);
                } else {
                    SkipUtil.skipToAddUserOperate(LoginActivity.this, getOwnerName(), 21, 0, "发送登录验证码失败", "", "", phone);
                }
                time = 0;
                handler.sendEmptyMessageDelayed(WHAT_TIMW, 1000);
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
                SkipUtil.skipToAddUserOperate(LoginActivity.this, getOwnerName(), 21, 0, "发送登录验证码失败", "", "", phone);
                toast(R.string.get_verification_failed);
//                if (TextUtils.isEmpty(errorMsg)) {
//                } else {
//                    toast(errorMsg);
//                }
                btnCode.setEnabled(true);
            }
        });
    }

    private ArrayMap<String, Object> getLoginParam(PlatformDb db) {
        ArrayMap<String, Object> para = new ArrayMap<>();
        boolean b = db != null;
        para.put("isOpenLogin", b);
        if (b) {
            para.put("openAvatar", db.getUserIcon());
            para.put("openId", db.getUserId());
            para.put("openName", db.getUserName());
            para.put("openType", openType);
        } else {
            para.put("authCode", etCode.getText().toString());
            para.put("phoneNumber", etPhone.getText().toString());
        }
        JLog.e("getLoginParam", "----" + para.toString());
        return para;
    }

    private synchronized void login(PlatformDb db) {
        btnLogin.setEnabled(false);
        final String phone = etPhone.getText().toString();
        ArrayMap<String, Object> map = getLoginParam(db);
        showProgress("正在登录中...");
        NetUtils.getNetAdapter().postLogin(getOwnerName(), map, new AbsNetCallBack<FUsers>(FUsers.class, db) {
            @Override
            public void onSuc(FUsers fUsers) {
                if (fUsers != null) {
                    btnLogin.setEnabled(true);
                    if (obj != null && obj instanceof PlatformDb) {
                        if (TextUtils.isEmpty(fUsers.getAvatar())) {
                            PlatformDb pdb = (PlatformDb) obj;
                            if (!TextUtils.isEmpty(pdb.getUserIcon())) {
                                fUsers.setAvatar(pdb.getUserIcon());
                            }
                        }
                        fUsers.setBindType(openType);
                    }
                    UserManager.getInstance().setUser(LoginActivity.this, fUsers);
                    SkipUtil.skipToAddUserOperate(LoginActivity.this, getOwnerName(), 21, 0, "登录成功", "", "");
                    Handler loginHandler = new Handler();
                    loginHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            closeProgress();
                            toast(R.string.login_suc);
                            setResult(RESULT_OK);
                            finish();
                        }
                    }, 1500);

                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
                btnLogin.setEnabled(true);
                if (TextUtils.isEmpty(phone)) {
                    SkipUtil.skipToAddUserOperate(LoginActivity.this, getOwnerName(), 21, 0, "登录失败", "", "");
                } else {
                    SkipUtil.skipToAddUserOperate(LoginActivity.this, getOwnerName(), 21, 0, "登录失败", "", "", phone);
                }
                closeProgress();
                JLog.e("code=" + netCode + " msg=" + errorMsg + " ex=" + ex + "\n" + obj);
                if (netCode == CODE_ERROR_THIRD) {
                    if (obj != null && obj instanceof PlatformDb) {
                        PlatformDb pdb = (PlatformDb) obj;
                        toBindPhone(SerialThirdInfo.from(pdb, openType));
                    }
                } else {
                    toast("登录失败");
                }
            }
        });
    }

    private void toBindPhone(SerialThirdInfo info) {
        Intent intent = new Intent(this, BindPhoneActivity.class);
        intent.putExtra(BindPhoneActivity.EX_THIRD, info);
        startActivityForResult(intent, CODE_REQUEST_BIND);
    }

    private void parseMsg(Message msg) {
        int what = msg.what;
        if (what == WHAT_TIMW) {
            handler.removeMessages(WHAT_TIMW);
            time++;
            if (time > Time_Count) {
                btnCode.setText(R.string.get_agin);
                btnCode.setEnabled(true);
            } else {
                handler.sendEmptyMessageDelayed(WHAT_TIMW, 1000);
                btnCode.setText(String.format(getString(R.string.has_send_s), time));
            }
        } else if (what == WHAT_TIMW_STOP) {
            handler.removeMessages(WHAT_TIMW);
            btnCode.setEnabled(true);
        } else if (what == WHAT_LOGIN_THIRD) {
            if (msg.obj != null && (msg.obj instanceof PlatformDb)) {
                login((PlatformDb) msg.obj);
            }
        }
    }

    private void thirdLogin(String name) {
        Platform p = ShareSDK.getPlatform(name);
        p.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                PlatformDb db = platform.getDb();
                if (db != null) {
                    JLog.e(db.exportData());
                    Message msg = handler.obtainMessage(WHAT_LOGIN_THIRD, db);
                    handler.sendMessage(msg);
                } else {
                    JLog.e("login failed the platform db is null");
                }
                JLog.e("map=" + hashMap);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                JLog.e("login get error");
                if (throwable != null) {
                    throwable.printStackTrace();
                }
            }

            @Override
            public void onCancel(Platform platform, int i) {

            }
        });

        p.authorize();
//        p.showUser(null);
    }

    // 执行授权,获取用户信息
    // 文档：http://wiki.mob.com/Android_%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E8%B5%84%E6%96%99
    private void authorize(Platform plat) {
        // ShareSDK.initSDK(this);
        if (plat == null) {
            // popupOthers();
            return;
        }
        if (plat.isAuthValid()) {
            plat.removeAccount(true);
        }
//        if (plat.isAuthValid()) {
//            PlatformDb platformDb = plat.getDb();
//            if (platformDb.getUserId() != null) {
////                requestLoginThirdPart(platformDb.getUserId(), platformDb.getUserIcon(), platformDb.getUserName(),
////                        platformDb.getPlatformNname());
//                login(platformDb);
//                return;
//            }
//        }

        plat.setPlatformActionListener(this);
        // 关闭SSO授权
        plat.SSOSetting(false);
        plat.showUser(null);
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
//        System.out.println("第三方授权完成！" + action);
//        Toast.makeText(this, "第三方授权完成！" + action, Toast.LENGTH_SHORT).show();
        JLog.e("onComplete:" + platform.getName() + "  UserId:" + platform.getId());
        if (action == Platform.ACTION_USER_INFOR) {
            PlatformDb platDB = platform.getDb();// 获取数平台数据DB
            Message msg = new Message();
            msg.what = MSG_AUTH_COMPLETE;
            msg.obj = platform;
//                    new Object[]{platform.getName(), platDB.getUserId(), platDB.getUserIcon(),
//                    platDB.getUserName()};
            handlerLogin.sendMessage(msg);
            dialog.dismiss();
        }
    }

    @Override
    public void onError(Platform platform, int action, Throwable throwable) {
        JLog.e(" ThirdLogin onError:" + platform.getName() + "  UserId:" + platform.getId() + "MSG = " + throwable.getMessage() + "----" + throwable.getLocalizedMessage());
        if (action == Platform.ACTION_USER_INFOR) {
            handlerLogin.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        throwable.printStackTrace();
        dialog.dismiss();
    }

    @Override
    public void onCancel(Platform platform, int i) {
        dialog.dismiss();
        handlerLogin.sendEmptyMessage(MSG_AUTH_CANCEL);
    }

    private void initRule() {
        SpannableString spannableString = new SpannableString(getResources().getString(R.string.user_content4) +
                getResources().getString(R.string.user_agreement) +
                getResources().getString(R.string.user_content2) +
                getResources().getString(R.string.privacy_policy));

        spannableString.setSpan(new Clickable(this, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, UserAgreementActivity.class);
                intent.putExtra(UserAgreementActivity.RULE_TYPE, 0);
                startActivity(intent);
            }
        }, true), getResources().getString(R.string.user_content4).length(), getResources().getString(R.string.user_content4).length() + getResources().getString(R.string.user_agreement).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannableString.setSpan(new Clickable(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(LoginActivity.this, UserAgreementActivity.class);
                        intent.putExtra(UserAgreementActivity.RULE_TYPE, 1);
                        startActivity(intent);
                    }
                }, true), getResources().getString(R.string.user_content4).length()
                        + getResources().getString(R.string.user_agreement).length()
                        + getResources().getString(R.string.user_content2).length(),
                getResources().getString(R.string.user_content4).length()
                        + getResources().getString(R.string.user_agreement).length()
                        + getResources().getString(R.string.user_content2).length()
                        + getResources().getString(R.string.privacy_policy).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        content.setText(spannableString);
        content.setMovementMethod(LinkMovementMethod.getInstance());
    }
}
